'''
Created on 29 Nov 2012

@author: quirino.brizi
'''
from cupy.connectionpool import HTTPConnectionPool, AsyncHTTPConnectionPool
from cupy.messages import Request
from time import sleep
import unittest

class HTTPConnectionPoolTest(unittest.TestCase):
    
    def setUp(self):
        self.cp = HTTPConnectionPool(host="http://localhost:8000", port=80)
        self.assertIsNotNone(self.cp, "Unable to initialise connection poll")
        self.assertEqual("http://localhost:8000", self.cp.host, 
                         "Host name has been set to an unexpected value")
        self.assertEquals(80, self.cp.port, 
                          "Port has been set to an unexpected value")
    
    def test_getconn(self):
        conn = self.cp._getconn()
        self.assertIsNotNone(conn, "_getconn return a None connection");
    
    def test_puconn(self):
        self.assertEquals(0, getattr(self.cp, 'active'),
            "Newly created pool the number of active connections should be 0")
        conn = self.cp._getconn()
        self.assertIsNotNone(conn, "_getconn return a None connection");
        self.assertEquals(1, getattr(self.cp, 'active'),
            "Newly created pool the number of active connections should be 0")
        pool = getattr(self.cp, 'pool')
        active = 0
        queue = getattr(pool, 'queue');
        self.assertIsNotNone(queue)
        for c in queue : 
            if c is not None : active += 1
        self.assertEquals(0, active, 
            "Number of active connections doesn't match the expected 0 != %s" % 
            (active))
        
        self.cp._putconn(conn);
        
        queue = getattr(pool, 'queue');
        for c in queue : 
            if c is not None : active += 1
        self.assertEquals(1, active, 
            "Number of active connections doesn't match the expected 1 != %s" % 
            (active))
    
    def test_close(self):
        self.assertEquals(0, getattr(self.cp, 'active'),
            "Newly created pool the number of active connections should be 0")
        pool = getattr(self.cp, 'pool')
        self.assertEquals(10, pool.qsize(),
            "Newly created default pool size should be 10 got %d" % pool.qsize())
        self.cp.close()
        self.assertEquals(0, getattr(self.cp, 'active'),
            "Newly created pool the number of active connections should be 0")
        self.assertEquals(0, pool.qsize(),
            "Closed pool size should be 0 got %d" % pool.qsize())
        
    def test_urlopen_basic(self):
        req = Request(url="http://localhost:8000")
        resp = self.cp.urlopen(req)
        self.assertIsNotNone(resp, "Got None response from urlopen")
        url = resp.get_url()
        self.assertEquals("http://localhost:8000", url, 
                          "Expected URL: http://localhost:8000, got %s" % url)
        self.assertIsNotNone(resp.get_body(), "Got None body from response")
        self.assertIsNotNone(resp.get_headers(),
                             "Got None headers from response")
        info = resp.get_info()
        self.assertIsNotNone(info, "Got None body from response")
        self.assertEquals(31, len(info), 
                          "Expected 31 properties got %d" % len(info))
        self.assertIsNotNone(info["TOTAL_TIME"], 
                             "Invalid transaction information map content")
        
class AsyncHTTPConnectionPoolTest(unittest.TestCase):
    
    def test_urlopen_ok(self):
        requests = [Request(url="http://localhost:8000"),
               Request(url="http://localhost:8000")]
        async = AsyncHTTPConnectionPool()
        futures = async.urlopen(requests)
        self.assertEquals(len(requests), len(futures))
        
        nr = 0
        for future in futures:
            if future.isready() and not future.iscollected():
                try :
                    resp = future.get()
                    self.assertIsNotNone(resp)
                    self.assertIsNotNone(resp.get_info())
                except :
                    pass
                nr+=1
            sleep(0.5)
        
        async.close()
        self.assertEquals(len(futures), nr)